package controller.login;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import java.io.IOException;

import define.Key;
import ui.activity.login.Login;

//import com.google.android.gms.gcm.GoogleCloudMessaging;

public class RegisterGCMClientAsync extends AsyncTask<Void, Void, String> {

    /**
     * String section
     */

    /**
     * The others section
     */
    private GoogleCloudMessaging mGcm;
    private Context mContext;

    /**
     * @param mContext
     */
    public RegisterGCMClientAsync(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * Registers the application with GCM servers asynchronously.
     * <p/>
     * Stores the registration ID and app versionCode in the application's
     * shared preferences.
     */
    @Override
    protected String doInBackground(Void... params) {
        String REGISTERED_GCM_ID = "";
        try {
            //initial GCM
            mGcm = GoogleCloudMessaging.getInstance(mContext);
            //get REGISTERED_GCM_ID
            REGISTERED_GCM_ID = mGcm.register(Key.PROJECT_NUMBER_ON_GOOGLE_CONSOLE);

            // You should send the registration ID to your server over HTTP,
            // so it can use GCM/HTTP or CCS to send messages to your app.
            // The request to your server should be authenticated if your app
            // is using accounts.
            sendRegistrationIdToBackend();

            // For this demo: we don't need to send it because the device
            // will send upstream messages to a server that echo back the
            // message using the 'from' address in the message.
        } catch (IOException ex) {
            REGISTERED_GCM_ID = "Error :" + ex.getMessage();
            // If there is an error, don't just keep trying to register.
            // Require the user to click a button again, or perform
            // exponential back-off.
        }
        return REGISTERED_GCM_ID;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        Log.i("", "REGISTERED_GCM_ID : " + result);
        Login.mSpEditor.putString(Key.DEVICE_TOKEN, result);
        Login.mSpEditor.commit();
         // Save REGISTERED_GCM_ID to single ton.
        Login.user.setDeviceToken(result);
//        Cloudstringers.user.setRegistrationID(result);
    }

    /**
     * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP
     * or CCS to send messages to your app. Not needed for this demo since the
     * device sends upstream messages to a server that echoes back the message
     * using the 'from' address in the message.
     */
    private void sendRegistrationIdToBackend() {
        // Your implementation here.
    }
}
